import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Dimensions, KeyboardAvoidingView, Platform, ScrollView, TouchableOpacity, Image, TextInput,
	DeviceEventEmitter
} from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { RadoiCpt } from './_components/form/RadoiCpt';
import { AttachmentCpt } from './_components/form/AttachmentCpt';
import { SelectCpt } from './_components/form/SelectCpt';
import { CheckBoxCpt } from './_components/form/CheckBoxCpt';
import { AddressCpt } from './_components/form/AddressCpt';
import { RemarkCpt } from './_components/form/RemarkCpt';
import { GoodsModuleCpt } from './_components/form/GoodsModuleCpt';
import OfferAPIService from './_common/OfferAPIService';
import DatePicker from '../../../component/DatePicker';
import OfferCreateMethods from './OfferCreateMethods';
import { offerStyle } from './_components/form/offerStyle';
import { showMap, initDate, title } from './_components/form/offerMap';
import Utils from '../../../utils/utils';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;

/*
	参数
	salesType: 类型 采销 必
	bidPackageApplyId:'' 编辑用  (草稿用)
	isCopy : 是否是再来
*/
/*
bizType: 
ADD：新增
COPY:复制场次
READD：再来一轮
EDIT：编辑
 */




export class OfferCreatePage extends Component {
	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		console.log('报盘新增模块-传参数', params)
		return {
			headerTitle: `新增${params.salesType == 'S' ? '销售' : '采购'}资源`,
			headerTintColor: style.color.white,//
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color="#fff" />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: style.head.headerTitleStyle
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			pageState: 'loading',
			goodsCateIds: [],
			refuseModalVisible: false
		}
		//表单提交参数
		this.sendData = OfferCreateMethods.defualtParams(props);
	}

	componentWillMount() {
		this._init();
	}

	componentWillUnmount() {
		this.sendData = null;
		this.setState = () => {
			return
		}
	}

	_init = async () => {
		await this._getDictList();
		await this._editor();
		this.setState({
			pageState: 'data'
		})
	}

	//编辑
	_editor = async () => {
		let { bidPackageApplyId, isCopy } = this.props.navigation.state.params || {};
		if (!bidPackageApplyId) return;
		let editorRes = await OfferAPIService.offerEdit({ bidPackageApplyId, bizType: isCopy ? 'COPY' : null });
		console.log('editorRes-编辑', editorRes)
		if (editorRes && editorRes.bidPackageApplyId) {
			this.sendData.bizType = isCopy ? 'COPY' : 'EDIT'; // 标记一下 是草稿还是拷贝
			this.sendData.packageApplyInfo = this._modifyData(editorRes);
			this.setState({
				fileIdArry: editorRes.fileIdArry
				// fileIdArry: ['21030414520490432116635129', '21030414521970372390151129', '20101910105875619913315129']
			})
		}
		if (editorRes.resourceApplyList) {
			let arr = []
			editorRes.resourceApplyList.map(item => {
				if (item.goodsCateId) {
					arr.push(item.goodsCateId)
				}
			})
			this.setState({
				goodsCateIds: arr
			})
		}
	}

	//修改数据
	_modifyData = (editorRes) => {
		let { resourceApplyList, priceType, bizModel } = editorRes || {};
		if (priceType) { // 处理价格类型(主项下放到子项)
			resourceApplyList && resourceApplyList.map((item) => {
				item.priceType = priceType;
				item.symbol = item.udPrice >= 0 ? true : false; //升贴水
				//item.udPrice = Math.abs(item.udPrice);
				// 如果是 招标和需求判断 进来的编辑  清空 报盘低价
				if (bizModel === 'Z' || bizModel === 'DD') {
					item.offerBottomPrice = null;
				}
				return item;
			})
		}
		if (this.sendData.bizType === 'COPY') { // 复制场次 清空属性
			editorRes.isCustIntentionPlan = null;// 是否客户按日提报日期
			editorRes.intentionPlanBeginDate = null;
			editorRes.intentionPlanEndDate = null;
			editorRes.deliveryBeginDate = null; //交货期限
			editorRes.deliveryEndDate = null;
			editorRes.upTime = null; //计划上架时间
		}
		return editorRes;
	}

	//获取数据库字典
	_getDictList = async () => {
		let { salesType } = this.sendData.packageApplyInfo || {};
		this.businessTypeData = await OfferCreateMethods.getDict('CRM_IS_UNIT');   // 业务类型
		this.offerTypeData = await OfferCreateMethods.getDict('CRM_RULE_BIZ_MODEL');   // 报盘类型
		this.offerTypeData = this.offerTypeData.filter(item => item.dictKey != "OT");
		this.areaData = await OfferCreateMethods.getDict('EC_PRICE_REGION');  // 销售区域
		this.payTypeData = await OfferCreateMethods.getDict('EC_PAY_TYPE'); // 付款类型
		this.payMethodData = await OfferCreateMethods.getDict('EC_PAY_METHOD');  //付款方式
		this.deliveryData = await OfferCreateMethods.getDict(salesType == 'S' ? 'CRM_SALES_DELIVERY_TYPE' : 'CRM_PURCHASE_DELIVERY_TYPE');//交货方式
		this.transportTypeData = await OfferCreateMethods.getDict('CRM_RESOURCE_TRANSPORT_TYPE'); // 运输方式
		this.cargoTypeData = await OfferCreateMethods.getDict('CRM_RESOURCE_CARGO_TYPE'); //货物类型
		this.timeTypeData = await OfferCreateMethods.getDict('CRM_EFFECTIVE_TIME_TYPE');//资源有效时段
		this.yesAndNoData = await OfferCreateMethods.getDict('Y_OR_N');//是和否  是否客户填报意向计划 是否需要转成交报告
		this.priceTypeData = await OfferCreateMethods.getDict('EC_PRICE_TYPE'); //价格类型 一口价 暂定价
	}


	//回调
	_baseCallBack = (data) => {
		console.log('data', data)
		let { packageApplyInfo } = this.sendData || {};
		this.sendData.packageApplyInfo = Object.assign({}, packageApplyInfo, data);
		for (var key in data) {
			if (key === 'bizModel') { // 如果是报盘 刷新页面
				this.sendData.packageApplyInfo.salesRuleId = ''
				this.sendData.packageApplyInfo.ruleName = ''
				this.sendData.packageApplyInfo.goodsCateId = ''
				this.sendData.packageApplyInfo.resourceApplyList = []
				this._clearTarget()
				// this._clearProduct(data, key)
			} else if (key === 'ruleName') {
				this._clearProduct()
				this._clearTarget()
			}
			else if (key === 'areaId') {
				this._clearTarget()
			}
			else if (key != 'tranDesc' || key != 'applyRemark') {
				this.setState({ ls: true })
			}
		}
		console.log('基本-回调', data, this.sendData)
	}
	//清除定向
	_clearTarget = () => {
		let packageApplyInfo = this.sendData.packageApplyInfo
		packageApplyInfo.areaIds = []
		packageApplyInfo.companyTypeIds = []
		packageApplyInfo.resourceGroupIdArry = []
		packageApplyInfo.channel = ''
		this.setState({ ls: true });
	}
	//清除采销
	_clearProduct = () => {
		let { bizModel } = this.sendData.packageApplyInfo
		this.sendData.packageApplyInfo.resourceApplyList = []
		DeviceEventEmitter.emit('clear', true)
		if (bizModel === "Z" || bizModel === "DD") { // 招标
			if (!this.sendData.packageApplyInfo.isFullPricesRequired) this.sendData.packageApplyInfo.isFullPricesRequired = 'Y';  //是否所有价格必填
			if (!this.sendData.packageApplyInfo.isFullPackageFix) this.sendData.packageApplyInfo.isFullPackageFix = 'Y';  //是否整包提报
		}
		if (bizModel === "P") {
			if (!this.sendData.packageApplyInfo.isSubmitPrepay) this.sendData.packageApplyInfo.isSubmitPrepay = 'N';  //是否缴纳保证金
		}
		this.sendData.packageApplyInfo = initDate.bizModel(this.sendData.packageApplyInfo, bizModel); //处理数据
		this.setState({
			goodsCateIds: []
		})
	}
	//商品回调数据
	_goodsCallback = (data) => {
		console.log('商品', data)
		this.sendData.packageApplyInfo.resourceApplyList = OfferCreateMethods.goodsCallback(data);;
		let arr = []
		data.map(item => {
			if (item.goodsCateId) {
				arr.push(item.goodsCateId)
			}
		})
		//判断是否是商品变化，商品变化则清空定向客户
		if (this.state.goodsCateIds.toString() !== arr.toString()) {
			this._clearTarget()
		}
		this.setState({
			goodsCateIds: arr
		})
		let { sendData, isRefresh } = OfferCreateMethods.zhaoPriceSubmit(this.sendData);
		this.sendData = sendData;
		if (isRefresh) this.setState({ ls: true });
	}


	//计划上架时间 弹框
	_openTimeFn = () => {
		this.DatePicker.show();
	}

	//仓库地址
	_AddCallBackFn = (data) => {
		console.log('仓库地址回调-总', data);
		if (!data) return;
		this.sendData.packageApplyInfo.warehouseAddressIdArry = data.warehouseAddressIdArry;
		this.sendData.packageApplyInfo.warehouseAddressNameArry = data.warehouseAddressNameArry;
	}

	showPackageName = async () => {
		this.sendData.load = true;
		if (OfferCreateMethods.validation(this.sendData)) {
			this.sendData.load = false;
			return this.sendData;
		}
		if (this.sendData.bizType === 'EDIT') {
			this.sendData.load = false;
			this.setState({
				refuseModalVisible: true
			})
		} else {
			let res = await HTTP.POST(API_GENERATE(API.PACKAGE_APPLY_NAME), this.sendData);
			this.sendData.load = false;
			if (res) {
				this.sendData.packageApplyInfo.bidPackageName = res
				this.setState({
					refuseModalVisible: true
				})
			}
		}

	}

	render() {
		let { pageState, fileIdArry, goodsCateIds } = this.state;
		let { packageApplyInfo } = this.sendData || {};
		let { bizModel, areaId, isUnite, isFullPricesRequired, isFullPackageFix, isSubmitPrepay,
			isMustTran, effectiveTimeType, payTypeArry, payStyleArry, deliveryTypeArry, transportTypeArry, deliveryBeginDate, deliveryEndDate,
			upTime, warehouseAddressIdArry, warehouseAddressNameArry, prepay, isCustIntentionPlan, cargoType, resourceApplyList, tranDesc,
			intentionPlanBeginDate, intentionPlanEndDate, salesType, effectiveHour, effectiveMinute, auditRemark, applyRemark, prepayRate,
			ruleName, salesRuleId, channel, resourceGroupIds, companyTypeIds, areaIds
		} = packageApplyInfo || {};
		console.log('0000000000-------------------------------render', packageApplyInfo);
		return (
			<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>

				{
					pageState === 'data' ? (
						<View style={{ flex: 1, position: 'relative' }}>
							<ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps={'handled'}>
								<View style={styles.ScrollViewInner}>
									<View style={styles.box}>
										<RadoiCpt data={{
											id: 'isUnite',
											selectKey: isUnite,
											title: '业务类型',
											listData: this.businessTypeData,
											required: true
										}}
											callBack={this._baseCallBack}
										/>
										<SelectCpt
											data={{
												id: 'bizModel',
												title: '报盘类型',
												listData: this.offerTypeData,
												selectKey: bizModel,
												salesType,
												required: true
											}}
											callBack={this._baseCallBack}
										/>
										<SelectCpt
											data={{
												id: 'areaId',
												title: title.area[salesType],
												selectKey: areaId,
												listData: this.areaData,
												salesType,
												required: true
											}}
											callBack={this._baseCallBack}
										/>
										{salesType === 'S' ?
											<SelectCpt
												data={{
													id: 'purRule',
													title: '采销规则',
													required: true,
													salesType,
													bizModel,
													selectKey: salesRuleId,
													priceFormlaName: ruleName
												}}
												callBack={this._baseCallBack}
											/> : null
										}
										{
											(salesType === 'P' && bizModel) || (salesType === 'S' && ruleName) ? <View>
												<GoodsModuleCpt dictionaryData={this.priceTypeData} data={{ bizModel, salesType, editeData: resourceApplyList, salesRuleId }} goodsCallback={this._goodsCallback} />
												{
													showMap.isFullPricesRequiredFn(bizModel, resourceApplyList) ? <RadoiCpt data={{
														id: 'isFullPricesRequired',
														title: '是否所有价格必填',
														listData: this.yesAndNoData,
														selectKey: isFullPricesRequired,
														layStyle: offerStyle.layStyle
													}}
														callBack={this._baseCallBack}
													/> : null
												}
												{
													showMap.isFullPackageFixFn(bizModel, resourceApplyList) ? <RadoiCpt data={{
														id: 'isFullPackageFix',
														title: '是否整包提报',
														listData: this.yesAndNoData,
														selectKey: isFullPackageFix,
														layStyle: offerStyle.layStyle,
													}}
														callBack={this._baseCallBack}
													/> : null
												}
												{
													showMap.isSubmitPrepayFn(bizModel) ? <RadoiCpt data={{
														id: 'isSubmitPrepay',
														title: '是否缴纳保证金',
														listData: this.yesAndNoData,
														selectKey: isSubmitPrepay,
														layStyle: offerStyle.layStyle,
														other: { id: 'prepay', value: prepay, type: 'input', lay: '¥', unit: '元', otherKey: 'Y' }
													}}
														callBack={this._baseCallBack}
													/> : null
												}
												{salesType === 'S' ?
													<SelectCpt
														data={{
															id: 'TargetCus',
															title: '定向客户',
															required: true,
															salesType,
															goodsCateIds,
															areaId,
															targetData: {
																channel,
																resourceGroupIds,
																companyTypeIds,
																areaIds
															},
															priceFormlaName: channel == '1' ? '已按群组选择' : channel == '2' ? '已按类型选择' : null
														}}
														callBack={this._baseCallBack}
													/> : null
												}
												<RadoiCpt data={{
													id: 'isMustTran',
													title: '是否需要转成交',
													listData: this.yesAndNoData,
													selectKey: isMustTran,
													layStyle: offerStyle.layStyle,
												}}
													callBack={this._baseCallBack}
												/>
												<RadoiCpt data={{
													id: 'isCustIntentionPlan',
													title: title.submission[salesType],
													listData: this.yesAndNoData,
													selectKey: isCustIntentionPlan,
													layStyle: offerStyle.layStyle,
													required: true,
													other: {
														idStaet: 'intentionPlanBeginDate',
														idEnd: 'intentionPlanEndDate',
														valueStart: intentionPlanBeginDate,
														valueEnd: intentionPlanEndDate,
														intentionPlanBeginDate,
														intentionPlanEndDate,
														type: 'time-day',
														otherKey: 'Y'
													}
												}}
													callBack={this._baseCallBack}
												/>
												<RadoiCpt data={{
													id: 'effectiveTimeType',
													title: '资源有效时段',
													listData: this.timeTypeData,
													selectKey: effectiveTimeType,
													layStyle: offerStyle.layStyle,
													other: { type: 'time-hours', effectiveHour, effectiveMinute, otherKey: 'O' }
												}}
													callBack={this._baseCallBack}
												/>
												<RadoiCpt data={{
													id: 'upTime',
													title: '计划上架时间',
													listData: [],
													layStyle: offerStyle.layStyle,
													selectKey: upTime,
													required: true
												}}
													callBack={this._openTimeFn}
												/>
												<AttachmentCpt data={{
													title: '附件',
													fileIdArry: fileIdArry
												}}
													getItemInfo={(val) => {
														this.sendData.packageApplyInfo.resourceBidPackageFileVOS = val
														console.log(val)
													}}
													propsData={this.props}
												/>
												<AddressCpt
													data={{ eidtData: { warehouseAddressIdArry, warehouseAddressNameArry } }}
													callBack={this._AddCallBackFn}
												/>

												<CheckBoxCpt
													data={{
														type: 'time-day',
														title: '交货期限',
														other: {
															idStaet: 'deliveryBeginDate',
															idEnd: 'deliveryEndDate',
															valueStart: deliveryBeginDate,
															valueEnd: deliveryEndDate
														}
													}}
													callBack={this._baseCallBack}
												/>
												<RadoiCpt data={{
													id: 'cargoType',
													title: '质量标准',
													listData: this.cargoTypeData,
													selectKey: cargoType,
													layStyle: { width: 80 * scale }
												}}
													callBack={this._baseCallBack}
												/>
												<CheckBoxCpt
													data={{
														id: 'payTypeArry',
														title: '付款类型',
														listData: this.payTypeData,
														selectKeyArr: payTypeArry || [],
														layStyle: { width: 80 * scale },
														prepayRate: prepayRate
													}}
													callBack={this._baseCallBack}
												/>
												<CheckBoxCpt
													data={{
														id: 'payStyleArry',
														title: '付款方式',
														listData: this.payMethodData,
														selectKeyArr: payStyleArry || [],
														layStyle: { width: 80 * scale }
													}}
													callBack={this._baseCallBack}
												/>
												<CheckBoxCpt
													data={{
														id: 'deliveryTypeArry',
														title: '交付方式',
														listData: this.deliveryData,
														selectKeyArr: deliveryTypeArry || [],
														layStyle: { width: 80 * scale }
													}}
													callBack={this._baseCallBack}
												/>
												<CheckBoxCpt
													data={{
														id: 'transportTypeArry',
														title: '运输方式',
														listData: this.transportTypeData,
														selectKeyArr: transportTypeArry || [],
														layStyle: { width: 80 * scale }
													}}
													callBack={this._baseCallBack}
												/>
												{/* <RemarkCpt data={{
													id: 'tranDesc',
													title: '特别说明',
													selectKey: tranDesc,
												}}
													callBack={this._baseCallBack}
												/> */}
												{/* <RemarkCpt data={{
													id: 'applyRemark',
													title: '送审备注',
													selectKey: applyRemark,
												}}
													callBack={this._baseCallBack}
												/> */}
												<View >
													<Text >{'特别说明' || '-'}</Text>
													<TextInput underlineColorAndroid='transparent' style={[offerStyle.fontBold, styles.textArea]} defaultValue={Utils.numberToString(tranDesc)} multiline={true} numberOfLines={6} maxLength={2000} placeholder='限定2000字' onChangeText={(value) => {
														this.sendData.packageApplyInfo.tranDesc = value;
													}} />
												</View>
												<View >
													<Text >{'送审备注' || '-'}</Text>
													<TextInput underlineColorAndroid='transparent' style={[offerStyle.fontBold, styles.textArea]} defaultValue={Utils.numberToString(applyRemark)} multiline={true} numberOfLines={6} maxLength={2000} placeholder='限定2000字' onChangeText={(value) => {
														this.sendData.packageApplyInfo.applyRemark = value;
													}} />
												</View>
											</View> : null
										}
									</View>
								</View >
							</ScrollView>
							<View style={styles.btnBoxBig}>
								<View style={styles.btnBox}>
									<TouchableOpacity style={styles.BtnBg} onPress={async () => {
										if (this.sendData.load) return;
										this.sendData.saveType = "SAVE";
										this.showPackageName()
										// this.sendData = await OfferCreateMethods.submit(this.sendData);
										console.log('this.sendData-00120210120120', this.sendData)
									}}>
										<Text style={styles.BtnText}>保存</Text>
									</TouchableOpacity>
									<TouchableOpacity style={[styles.BtnBg, styles.BtnBgR]} onPress={async () => {
										if (this.sendData.load) return;
										this.sendData.saveType = "SUBMIT";
										this.showPackageName()
										// this.sendData = await OfferCreateMethods.submit(this.sendData);
									}}>
										<Text style={styles.BtnText}>提交申请</Text>
									</TouchableOpacity>
								</View>
							</View>

						</View>
					) : (<View style={styles.statusStyle}><PageStatusIndex status={pageState} /></View>)
				}
				<DatePicker
					unit={['年', '月', '日']}
					startYear={2000}
					endYear={2100}
					onPickerConfirm={(timeArr) => {
						let timeStr = '';
						timeArr && timeArr.forEach((item, index) => {
							item = item.substring(0, item.length - 1);
							if (index < 2) {
								timeStr += item + '-';
							}
							else if (index == 2) {
								timeStr += item
							} else if (index == 3) {
								timeStr += " " + item
							} else if (index == 4) {
								timeStr += ":" + item;
							}
							console.log('timeStr999', timeStr)
						})
						this.sendData.packageApplyInfo.upTime = timeStr;
						this.setState({ ls: true })
						console.log('	this.sendData.packageApplyInfo', this.sendData.packageApplyInfo)
					}}
					onPickerCancel={() => {
						console.log('cancel');
					}}
					ref={ref => this.DatePicker = ref} />
				<RefuseModal
					titleText={'当前资源包名称'}
					placeholderText={'请输入资源包名称'}
					propsDefaultValue={this.sendData.packageApplyInfo.bidPackageName}
					visible={this.state.refuseModalVisible}
					btnPress={(bidPackageName) => {
						this.sendData.packageApplyInfo.bidPackageName = bidPackageName;
						OfferCreateMethods.submit(this.sendData)
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						})
					}}
				/>
			</KeyboardAvoidingView>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#E8ECF5',
	},
	ScrollViewInner: {
		marginBottom: 80 * scale
	},
	statusStyle: {
		flex: 1,
		position: 'absolute',
		height: '100%',
		width: Dimensions.get('window').width,
		top: 0,
		left: 0,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center'
	},
	box: {
		marginHorizontal: 20 * scale,
		paddingVertical: 10 * scale
	},
	btnBoxBig: {
		position: 'absolute',
		bottom: 0,
		left: 0,
		width: '100%',
		height: 80 * scale,
		backgroundColor: '#E8ECF5',
	},
	btnBox: {
		flexDirection: 'row',
		justifyContent: 'center',
		marginVertical: 20 * scale,
	},
	BtnBg: {
		backgroundColor: style.color.themeColor,
		paddingHorizontal: 25 * scale,
		//paddingVertical: 10 * scale,
		height: 32 * scale,
		borderRadius: 15 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
	BtnText: {
		fontSize: 13 * scale,
		color: style.color.white
	},
	BtnBgR: {
		marginLeft: 30 * scale
	},
	textArea: {
		height: 64 * scale,
		backgroundColor: '#fff',
		marginTop: 10 * scale,
		borderRadius: 8 * scale,
		paddingHorizontal: 15 * scale,
		paddingVertical: 35 * scale,
		paddingVertical: 0,
		borderWidth: 0,
		marginBottom: 20 * scale
	}
})